import 'package:flutter/material.dart';
import 'package:safety_platform/bloc/task/task.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:safety_platform/components/loading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:safety_platform/models/task.dart';
import 'package:safety_platform/theme.dart';
import 'package:safety_platform/pages/task/task_detail_page.dart';
import 'package:safety_platform/utils.dart' show formatDate;

class TaskListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _TaskListPageState();
  }
}

class _TaskListPageState extends State<TaskListPage> {
  TaskListBloc _bloc;
  @override
  void initState() {
    super.initState();
    _bloc = TaskListBloc();
    _bloc.dispatch(QueryTodayTaskListEvent());
  }

  @override
  void dispose() {
    super.dispose();
    _bloc.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: _bloc,
      child: BlocBuilder(
        bloc: _bloc,
        builder: (BuildContext content, TaskListState state) {
          return Scaffold(
            resizeToAvoidBottomPadding: false,
            appBar: AppBar(
              title: new Text('今日任务'),
              elevation: 0,
              centerTitle: true, //设置标题是否局中
            ),
            body: _body(state),
          );
        },
      ),
    );
  }

  Widget _body(TaskListState state) {
    if (state is TaskListLoadingState) {
      return Loading();
    } else if (state is TaskListState) {
      print(state.results);
      if (state.results != null) {
        return TaskListWidget(
          data: state.results,
          onTaskPress: (Task task) {
            TaskDetailState detailState = TaskDetailState(task);
            Navigator.of(context).push(
                MaterialPageRoute(builder: (_) => TaskDetailPage(detailState)));
          },
          onRefresh: () =>
              _bloc.dispatch(QueryTodayTaskListEvent(throwLoadingState: false)),
        );
      }
    }
    return Center(child: Text('load..'));
  }
}

typedef OnTaskPress = Function(Task task);

class TaskListWidget extends StatefulWidget {
  // @override
  // void initState() {
  //   super.initState();
  // }\
  Function onRefresh;
  Function onLoadMore;
  OnTaskPress onTaskPress;

  TaskListWidget(
      {this.data, this.onRefresh, this.onLoadMore, this.onTaskPress});
  List<Task> data;
  @override
  State<StatefulWidget> createState() {
    return _TaskListWidgetState();
  }
}

class _TaskListWidgetState extends State<TaskListWidget> {
  GlobalKey<RefreshHeaderState>
      _headerKey; //= new GlobalKey<RefreshHeaderState>();
  GlobalKey<RefreshFooterState> _footerKey;
  GlobalKey<EasyRefreshState> _easyRefreshKey =
      new GlobalKey<EasyRefreshState>();

  @override
  void initState() {
    super.initState();
    _headerKey = GlobalKey<RefreshHeaderState>();
    _footerKey = GlobalKey<RefreshFooterState>();
  }

  Future<Null> _onRefresh() async {
    await widget.onRefresh();
    Future.value(null);
  }

  Future<Null> _loadMore() {}
  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
        refreshHeader: ClassicsHeader(
          key: _headerKey,
          bgColor: Colors.white70,
          textColor: Colors.black54,
          refreshText: '下拉刷新',
          refreshReadyText: '释放即开始刷新',
          refreshingText: '刷新中，请稍候..',
          refreshedText: '刷新完成',
        ),
        refreshFooter: ClassicsFooter(
          key: _footerKey,
          loadText: '上拉加载更多',
          noMoreText: '没有更多数据了',
          loadReadyText: '释放加载更多',
          loadingText: '正在加载，请稍候..',
          loadedText: '加载完成',
          bgColor: Colors.white70,
          // bgColor: Theme.of(context).backgroundColor,
          textColor: Colors.black54,
        ),
        key: _easyRefreshKey,
        autoControl: false,
        onRefresh: _onRefresh,
        loadMore: _loadMore,
        // enablePullDown: true,
        // enablePullUp: true,
        // onRefresh: _onRefresh,
        // controller: _controller,
        // footerConfig: LoadConfig(
        // bottomWhenBuild: false,
        // ),
        // headerBuilder: (BuildContext context, int mode) {
        //   return ClassicIndicator(
        //     mode: mode,
        //     refreshingText: '正在刷新',
        //     completeText: '刷新成功',
        //     idleText: '下拉刷新',
        //     releaseText: '下拉刷新',
        //   );
        // },
        // onOffsetChange: _onOffsetCallback,÷
        child: new ListView.builder(
          itemCount: widget.data.length,
          itemBuilder: _buildItem,
        ));
  }

  @override
  void didUpdateWidget(TaskListWidget oldWidget) {
    print('didUpdateWidget');
    super.didUpdateWidget(oldWidget);
    if (oldWidget != widget) {
      if (_easyRefreshKey != null) {
        if (_easyRefreshKey.currentState.isRefreshing) {
          _easyRefreshKey.currentState.callRefreshFinish();
        }
        _easyRefreshKey.currentState.callLoadMoreFinish();
      }
      // _headerKey.currentState.c
      // _headerKey.currentState.
      // if (_controller.isRefresh(true)) {
      // _controller.sendBack(true, RefreshStatus.completed);
    }
  }

  Widget _title(BuildContext context, Task task) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(bottom: 8),
      child: Text('${task.name}',
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            fontWeight: FontWeight.bold,
          )),
      decoration: BoxDecoration(
        border: Border(
            bottom: BorderSide(
          color: Color.fromARGB(255, 241, 241, 241),
          width: 0.5,
        )),
      ),
    );
  }

  Widget _description(BuildContext context, Task task) {
    String description = task.description ?? '暂无任务描述';

    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 8),
      child: Text(
        description,
        maxLines: 5,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  Widget _status(BuildContext context, Task task) {
    Color textColor;

    switch (task.status) {
      case 'pending':
        {
          textColor = pendigColor;
          break;
        }
      case 'done':
        {
          textColor = doneColor;
          break;
        }
      default:
        {
          textColor = Theme.of(context).textTheme.body1.color;
          break;
        }
    }
    return Container(
      width: double.infinity,
      // padding: EdgeInsets.symmetric(vertical: 4),
      child: Text(
        Task.transStatus(task.status),
        style: TextStyle(
          color: textColor,
        ),
      ),
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    Task task = widget.data[index];
    Color textColor;

    switch (task.status) {
      case 'pending':
        {
          textColor = pendigColor;
          break;
        }
      case 'done':
        {
          textColor = doneColor;
          break;
        }
      default:
        {
          textColor = Theme.of(context).textTheme.body1.color;
          break;
        }
    }
    return InkWell(
      child: Card(
        elevation: 0,
        child: Container(
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor,
            borderRadius: BorderRadius.circular(4.0),
          ),
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(3.5),
                        topRight: Radius.circular(3.5)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      _title(context, task),
                      _description(context, task),
                      _status(context, task),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: <Widget>[
                      //     Padding(
                      //         child: Text(
                      //           '任务名称',
                      //           style: TextStyle(
                      //             fontWeight: FontWeight.bold,
                      //           ),
                      //         ),
                      //         padding: EdgeInsets.symmetric(vertical: 4.0)),
                      //     Padding(
                      //         child: Text(
                      //           Task.transStatus(task.status),
                      //           style: TextStyle(color: textColor),
                      //         ),
                      //         padding: EdgeInsets.symmetric(vertical: 4.0)),
                      //     //      Padding(
                      //     //     child: Text(
                      //     //       '发布时间',
                      //     //       style: TextStyle(
                      //     //         fontWeight: FontWeight.bold,
                      //     //       ),
                      //     //     ),
                      //     //     padding: EdgeInsets.symmetric(vertical: 4.0)),
                      //     // Padding(
                      //     //     child: Text(
                      //     //       Task.transStatus(task.status),
                      //     //       style: TextStyle(color: textColor),
                      //     //     ),
                      //     //     padding: EdgeInsets.symmetric(vertical: 4.0)),
                      //   ],
                      // ),
                      // Text('${task.name}'),
                    ],
                  ),
                ),

                Container(
                  padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      task.extension != null? 
                        Padding(padding: EdgeInsets.symmetric(vertical: 4),
                        child: Text(
                          '涉及风险点: ${task.extension.riskName}',
                          overflow: TextOverflow.ellipsis,
                          style:TextStyle(color: Colors.white),
                        ),
                        ) :Container(),
                      Text(
                        '发布时间: ${formatDate(task.timePublished)}',
                        style: TextStyle(color: Colors.white),
                      )
                    ],
                  ),
                )
                // Container(
                //     padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
                //     child: Row(
                //       children: <Widget>[
                //         Expanded(
                //           flex: 1,
                //           child: Column(
                //             children: <Widget>[
                //               Text(
                //                 '涉及风险点',
                //                 style: TextStyle(
                //                   color: Colors.white,
                //                 ),
                //               ),
                //               Text(
                //                 '${task.extension.riskName}',
                //                 style: TextStyle(
                //                   color: Colors.white,
                //                 ),
                //               ),
                //             ],
                //           ),
                //         ),
                //         Expanded(
                //           flex: 1,
                //           child: Column(
                //             children: <Widget>[
                //               Text(
                //                 '发布时间',
                //                 style: TextStyle(
                //                   color: Colors.white,
                //                 ),
                //               ),
                //               Text(
                //                 '${task.timePublished}',
                //                 style: TextStyle(
                //                   color: Colors.white,
                //                 ),
                //               ),
                //             ],
                //           ),
                //         ),
                //       ],
                //     ))
              ]),
        ),
      ),
      onTap: () => widget.onTaskPress(task),
    );

    ///MediaQuery.of(context).size.width - 16 - 8 / 3;
    // print('statusWidth: ${statusWidth}');
  }
}
